<script setup>
import api from '../api/user_api.js'
import { ref, onMounted } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import lodash from 'lodash'

// 表格数据
const tableData = ref([])
const total = ref(0)

// 查询参数
const searchObj = ref({
  current: 1,
  limit: 10,
  username: '',
  email: ''
})

// 编辑/新增对象
const obj = ref({})
const editWinVisible = ref(false)

// 页面加载后挂载数据
onMounted(async () => {
  await search()
})

// 查询方法
const search = async () => {
  try {
    const res = await api.page(searchObj.value)
    tableData.value = res.data || []
    total.value = res.count || 0
  } catch (error) {
    console.error(error)
    tableData.value = []
    total.value = 0
  }
}

// 新增用户对象
const newUser = ref({})

// 控制新增对话框显示
const addWinVisible = ref(false)

const showAddDialog = () => {
  newUser.value = {}
  addWinVisible.value = true
}

const addCancel = () => {
  newUser.value = {}
  addWinVisible.value = false
}

// 提交新增
const addCommit = async () => {
  try {
    await api.add({ ...newUser.value })
    ElMessage({ message: '新增成功', type: 'success' })
    await search()
    addWinVisible.value = false
  } catch (error) {
    console.error(error)
    ElMessage({ message: '新增失败', type: 'error' })
  }
}

// 查询按钮点击
const handleSearch = () => {
  searchObj.value.current = 1
  search()
}

// 分页事件
const handleSizeChange = (val) => {
  searchObj.value.limit = val
  search()
}

const handleCurrentChange = (val) => {
  searchObj.value.current = val
  search()
}

// 取消编辑
const editCancel = () => {
  obj.value = {}
  editWinVisible.value = false
}

// 提交编辑
const editCommit = async () => {
  try {
    await api.edit(obj.value)
    editWinVisible.value = false
    await search()
    ElMessage({ message: '修改成功', type: 'success' })
  } catch (error) {
    console.error(error)
    ElMessage({ message: '修改失败', type: 'error' })
  }
}

// 编辑按钮点击
const handleEdit = (index, row) => {
  obj.value = lodash.cloneDeep(row)
  editWinVisible.value = true
}

// 删除按钮点击
const handleDelete = (index, row) => {
  ElMessageBox.confirm('确认删除该用户吗?', '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  })
      .then(async () => {
        await api.del(row.userId)
        searchObj.value.current = 1
        await search()
        ElMessage({ message: '删除成功', type: 'success' })
      })
      .catch(() => {})
}
</script>

<template>
  <div style="padding: 20px;">
    <h2>普通用户列表</h2>

    <!-- 查询框 -->
    <el-form :inline="true" :model="searchObj" style="margin-bottom: 10px;">
      <el-form-item label="用户名">
        <el-input v-model="searchObj.username" placeholder="请输入用户名" clearable/>
      </el-form-item>
      <el-form-item label="邮箱">
        <el-input v-model="searchObj.email" placeholder="请输入邮箱" clearable/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="handleSearch">查询</el-button>
        <el-button type="primary" @click="showAddDialog">新增用户</el-button>
      </el-form-item>
    </el-form>

    <!-- 新增用户对话框 -->
    <el-dialog v-model="addWinVisible" title="新增用户" width="500">
      <el-form :model="newUser" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="newUser.username"/>
        </el-form-item>
        <el-form-item label="密码">
          <el-input v-model="newUser.password" type="password" placeholder="请输入密码"/>
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="newUser.email"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="newUser.phone"/>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-select v-model="newUser.status" placeholder="请选择账号状态">
            <el-option label="正常" :value="0"/>
            <el-option label="禁用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="addCancel">取消</el-button>
          <el-button type="primary" @click="addCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 用户表格 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="userId" label="用户ID" width="80"/>
      <el-table-column prop="username" label="用户名" width="120"/>
      <el-table-column prop="email" label="邮箱" width="150"/>
      <el-table-column prop="phone" label="手机号" width="120"/>
      <el-table-column prop="status" label="账号状态" width="100">
        <template #default="scope">
          <el-tag :type="scope.row.status === 0 ? 'success' : 'danger'">
            {{ scope.row.status === 0 ? '正常' : '禁用' }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="注册时间" width="180"/>
      <el-table-column prop="updateTime" label="更新时间" width="180"/>
      <el-table-column label="操作" fixed="right" width="150">
        <template #default="scope">
          <el-button size="small" @click="handleEdit(scope.$index, scope.row)">编辑</el-button>
          <el-button size="small" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-pagination
        v-model:current-page="searchObj.current"
        v-model:page-size="searchObj.limit"
        :total="total"
        :page-sizes="[10,20,30,40]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
    />

    <!-- 编辑用户对话框 -->
    <el-dialog v-model="editWinVisible" title="编辑用户" width="500">
      <el-form :model="obj" label-width="100px">
        <el-form-item label="用户名">
          <el-input v-model="obj.username" autocomplete="off"/>
        </el-form-item>
<!--        <el-form-item label="密码">-->
<!--          <el-input v-model="obj.password" type="password" placeholder="不修改请留空" autocomplete="off"/>-->
<!--        </el-form-item>-->
        <el-form-item label="邮箱">
          <el-input v-model="obj.email" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="obj.phone" autocomplete="off"/>
        </el-form-item>
        <el-form-item label="账号状态">
          <el-select v-model="obj.status" placeholder="请选择账号状态">
            <el-option label="正常" :value="0"/>
            <el-option label="禁用" :value="1"/>
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="editCancel">取消</el-button>
          <el-button type="primary" @click="editCommit">提交</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<style scoped>
h2 {
  color: rgba(244, 64, 64, 0.35);
  margin-bottom: 20px;
}
</style>
